<?php

namespace app\admin\controller;

use app\admin\model\SystemAdmin;
use app\admin\model\SystemQuick;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Env;
use think\facade\Db;
use app\common\model\TicketDataModel;
/**
 * Class Admin
 * @package app\admin\controller\Index
 * @ControllerAnnotation(title="首页")
 */
class Index extends AdminController
{

    /**
     * 后台主页
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return $this->fetch('', [
            'admin' => session('admin'),
        ]);
    }

    /**
     * 后台欢迎页
     * @return string
     * @throws \Exception
     */
    public function welcome()
    {
        $quicks = SystemQuick::field('id,title,icon,href')
            ->where(['status' => 1])
            ->order('sort', 'desc')
            ->limit(8)
            ->select();
        $order=Db::name('order')->whereIn('orders_status',[1,2])->column('id');
        $ticket_price=0;
        $ticket_number=0;
        $house_number=0;
        $house_price=0;
        foreach ($order as $k => $v) {
            $order_server=Db::name('order_server')->where('order_id',$v)->select()->toArray();
            foreach ($order_server as $k1 => $v1) {
                if($v1['type']==1){
                    $ticket_number+=$v1['number'];
                    $ticket_price+=$v1['number']*$v1['act_price'];
                }elseif($v1['type']==2){
                        $house_number+=$v1['number'];
                        $house_price+=$v1['number']*$v1['act_price'];
                }
            }
        }
        $this->assign([
            'quicks'=>$quicks,
            'ticket_price'=>$ticket_price,
            'ticket_number'=>$ticket_number,
            'house_number'=>$house_number,
            'house_price'=>$house_price,

        ]);
        
        return $this->fetch();
    }

    /**
     * 修改管理员信息
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editAdmin()
    {
        $id  = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        empty($row) && $this->error('用户信息不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row
                    ->allowField(['head_img', 'phone', 'remark', 'update_time'])
                    ->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 修改密码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editPassword()
    {
        $id  = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        if (!$row) {
            $this->error('用户信息不存在');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [
                'password|登录密码'       => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }

            // 判断是否为演示站点
            $example = Env::get('easyadmin.example', 0);
            $example == 1 && $this->error('演示站点不允许修改密码');

            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="git版本更新")
     */
    public function gitUp()
    {
        // 远程版本
        $remote_version = input('version');
        $env_version    = env('app.version');
        $envPath = '../.env';
        if ((int) $remote_version > (int) $env_version) {
            // git reset --hard git pull
            $git_res = exec('git reset --hard');
            $git_res = exec('git pull');
            if (!$git_res) {
                $git_res = exec('git pull gitee master');
            }
            if (file_exists($envPath)) {
                $env = file_get_contents($envPath);
                $str = str_replace('VERSION=' . $env_version, 'VERSION=' . $remote_version, $env);
                file_put_contents($envPath, $str);
            } else {
                $this->error('.env文件不存在');
            }
            $this->error('更新成功！', $git_res);
        } else {
            $this->success('最新版本');
        }

    }

    /**
     * @NodeAnotation(title="获取版本")
     */
    public function getRemoteVersion()
    {
        $remote_version = input('version');
        $env_version    = env('app.version');
        if ((int) $remote_version > (int) $env_version) {
            $this->error('系统有新版本，建议更新！', $remote_version);
        }

        $this->success('最新版本');
    }
    // 首页订单数据分析
     public function getDataAnalysis(){
        $cycle=input('cycle')?input('cycle'):'thirtyday';
        $list=[];
        $count=[];
        $StoreDataModel=new TicketDataModel();
        $store=Db::name('ticket')->whereIn('id',[1,2,3,4,5,6,7])->field('id,title')->order('id asc')->select()->toArray();
     
        switch ($cycle) {
            case 'thirtyday':
                $date=$StoreDataModel->getData30Days();//近30天日期
               
                break;
            case 'week':
                $date=$StoreDataModel->get_weeks();//近1周日期列表
                break;
            case 'month':
                $date=$StoreDataModel->get_day_num();//本月日期列表
                break;
            case 'year':
                $date=$StoreDataModel->getDateMouth();//前12个月日期列表
                break;
        }
      
        $tmp_month=[];
        foreach($date as $k=>$v){
           foreach ($v as $kk => $vv) {
              array_push($tmp_month,$kk);
           }
        }
      
        $color=['#4B0082','#006400','#0000FF','#737300','#fsdf423'];
        foreach ($store as $k => $v) {
        
            $nums=$StoreDataModel->getOrdersPriceNumber($date,$v['id'],1,1); 
       
            
            $list[$k]["name"]     =$v['title'];
            $list[$k]['type']     ="bar";
            // $list[$k]["barGap"]   =0;
            // $list[$k]["label"]    ="labelOption";
            // $list[$k]["emphasis"] =array("focus"=>'series');
            // $list[$k]['itemStyle']=array(
            //     'normal'=>array('color'=>$color[$k])
            // );
          
            $list[$k]["data"]=$nums;
        }
  
        foreach ($store as $k => $v) {
            $nums=$StoreDataModel->getOrdersPriceNumber($date,$v['id'],2,1); 
            
            $count[$k]["name"]      =$v['title'];
            $count[$k]['type']      ="line";
            $count[$k]["yAxisIndex"]=1;
            $count[$k]["data"]      =$nums;
        }
        $data['lists']=array_merge($list,$count);
        $data['month']=$tmp_month;
        $data['names']=array_column($store,'title');
        $this->success('success',$data,200);
    }
     public function getDataAnalysisLease(){
        $cycle=input('cycle')?input('cycle'):'thirtyday';
        $list=[];
        $count=[];
        $StoreDataModel=new TicketDataModel();
        $store=Db::name('lease')->field('id,title')->order('id asc')->select()->toArray();
     
        switch ($cycle) {
            case 'thirtyday':
                $date=$StoreDataModel->getData30Days();//近30天日期
               
                break;
            case 'week':
                $date=$StoreDataModel->get_weeks();//近1周日期列表
                break;
            case 'month':
                $date=$StoreDataModel->get_day_num();//本月日期列表
                break;
            case 'year':
                $date=$StoreDataModel->getDateMouth();//前12个月日期列表
                break;
        }
      
        $tmp_month=[];
        foreach($date as $k=>$v){
           foreach ($v as $kk => $vv) {
              array_push($tmp_month,$kk);
           }
        }
      
        $color=['#4B0082','#006400','#0000FF','#737300','#fsdf423'];
        foreach ($store as $k => $v) {
        
            $nums=$StoreDataModel->getOrdersPriceNumber($date,$v['id'],1,2); 
       
            
            $list[$k]["name"]     =$v['title'];
            $list[$k]['type']     ="bar";
            // $list[$k]["barGap"]   =0;
            // $list[$k]["label"]    ="labelOption";
            // $list[$k]["emphasis"] =array("focus"=>'series');
            // $list[$k]['itemStyle']=array(
            //     'normal'=>array('color'=>$color[$k])
            // );
          
            $list[$k]["data"]=$nums;
        }
  
        foreach ($store as $k => $v) {
            $nums=$StoreDataModel->getOrdersPriceNumber($date,$v['id'],2,2); 
            
            $count[$k]["name"]      =$v['title'];
            $count[$k]['type']      ="line";
            $count[$k]["yAxisIndex"]=1;
            $count[$k]["data"]      =$nums;
        }
        $data['lists']=array_merge($list,$count);
        $data['month']=$tmp_month;
        $data['names']=array_column($store,'title');
        $this->success('success',$data,200);
    }
}
